package android.hermes;

import java.io.DataOutputStream;

public class AdHocWifiManager {
	
	
	
	
	 /**
     * @param role
     * @return
     * Sends linux root commands to set up the network
     */
    protected boolean enableWifi(int role) {
    	boolean runner = false;
    	runner = (runRootCommand("insmod /system/lib/modules/wlan.ko") &&
    	runRootCommand("wlan_loader -f /system/etc/wifi/Fw1251r1c.bin -e /proc/calibration -i /data/data/android.hermes/conf/tiwlan.ini") &&
    	runRootCommand("ifconfig tiwlan0 192.168.42.10"+role+" netmask 255.255.255.0") &&
    	runRootCommand("ifconfig tiwlan0 up"));
    	return runner;
    }
    
    /**
     * @return
     * disables the standard wifi
     */
    protected boolean disableWifi() {
    	boolean stopper = false;
    	stopper = (runRootCommand("ifconfig tiwlan0 down") &&
    	runRootCommand("rmmod wlan"));

    	return stopper;
    }

    /**
     * @return
     * connect to hermes with linux root command
     */
    protected boolean connect() {
    	return runRootCommand("system/bin/wpa_supplicant -i tiwlan0 -c /data/data/android.hermes/wpa.conf -B");
	}

    
    /**
     * @param command
     * @return
     * Executes a given command in a separate process as superuser
     * and returns true if there were no errors.
     */
    protected static boolean runRootCommand(String command) {
        Process process = null;
        DataOutputStream os = null;
		try {
			process = Runtime.getRuntime().exec("su");
	        os = new DataOutputStream(process.getOutputStream());
	        os.writeBytes(command+"\n");
	        os.writeBytes("exit\n");
	        os.flush();
	        process.waitFor();
		} catch (Exception e) {
			return false;
		}
		finally {
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (Exception e) {}
		}
		return true;
    }
}

